﻿using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using CsrdAPI.model.CompanyData;
using EntityFramework.Extensions;
using george.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CsrdAPI.Csrd;

namespace CsrdAPI
{
    [Description("公司资料管理")]
    public class CsrdCompanyHandler : BaseHandler
    {
        [MustLogin]
        [Description("获取公司列表")]
        [ReturnType(typeof(PaperData<ListData>))]
        public ApiResult GetList([ParamDescription("查询条件")] string SearchStr = "",
           [ParamDescription("页码")]int Page = 1,
           [ParamDescription("页数")]int Size = 10)
        {
            var dc = new CsrdEntities();
            var query = (from c in dc.Csrd_Company
                         join u in dc.Csrd_vm_user on c.Operator equals u.UserID
                         select new {
                             c,
                             u.UserName
                         });
            if (!string.IsNullOrWhiteSpace(SearchStr))
            {
                query = query.Where(t => t.c.CompanyName.Contains(SearchStr) || t.c.CompanyShortName.Contains(SearchStr));
            }
            var result = PaperData<ListData>.Create(query.Count(), Size, Page);
            result.Items = query.OrderByDescending(t => t.c.CreateDate).Skip(result.Skip)
                .Take(result.Limt).ToList()
                .Select(o => new ListData
                {
                    CompanyID = o.c.ID,
                    CompanyName = o.c.CompanyName,
                    CompanyShortName = o.c.CompanyShortName,
                    AccountCode = o.c.AccountCode,
                    BankName = o.c.BankName,
                    CompanyAddress = o.c.CompanyAddress,
                    TaxNumber = o.c.TaxNumber,
                    Telephone = o.c.Telephone,
                    CreateDate = (DateTime)o.c.CreateDate,
                    Operator = o.UserName,
                    Brand = (from b in dc.Csrd_Brand where b.CompanyID == o.c.ID select b.BrandName).FirstOrDefault()
                }).ToList();
            return Success(result);
        }

        [JsonType]
        [MustLogin]
        [Description("新增")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Create([ParamDescription("输入参数")] CreateData param)
        {
            if (param == null) return Error("对象为空！");
            if (string.IsNullOrWhiteSpace(param.CompanyName)) return Error("公司名称不能为空！");
            if (string.IsNullOrWhiteSpace(param.AccountCode)) return Error("帐号不能为空！");
            if (string.IsNullOrWhiteSpace(param.BankName)) return Error("开户行不能为空！");
            if (string.IsNullOrWhiteSpace(param.CompanyAddress)) return Error("公司地址不能为空！");
            if (string.IsNullOrWhiteSpace(param.TaxNumber)) return Error("税号不能为空！");
            if (string.IsNullOrWhiteSpace(param.Telephone)) return Error("联系电话不能为空！");
            if (string.IsNullOrWhiteSpace(param.Brand)) return Error("品牌不能为空！");
            if (param.CompanyShortName.Length > 100) return Error("【公司简称】长度超出限制");
            if (param.CompanyName.Length > 150) return Error("【公司名称】长度超出限制");
            if (param.AccountCode.Length > 20) return Error("【帐号】长度超出限制");
            if (param.BankName.Length > 50) return Error("【开户行】长度超出限制");
            if (param.CompanyAddress.Length > 200) return Error("【公司地址】长度超出限制");

            var dc = new CsrdEntities();

            if (dc.Csrd_Company.Any(t => t.CompanyName == param.CompanyName)) return Error("公司名称重复！");
            var r = param.Brand.TrimEnd(',').Split(',');
            if (r.Any(it => dc.Csrd_Brand.Any(t => t.BrandName.Contains(it))))
            {
                return Error($"品牌{param.Brand}已被使用！");
            }
            var add = new Csrd_Company{
               CompanyName = param.CompanyName,
               CompanyShortName = param.CompanyName,
               AccountCode = param.AccountCode,
               Telephone = param.Telephone,
               TaxNumber = param.TaxNumber,
               BankName = param.BankName,
               CompanyAddress= param.CompanyAddress,
               CreateDate = DateTime.Now,
               Operator = this.UserId
            };
            dc.Csrd_Company.Add(add);
            var brand = new Csrd_Brand
            {
                CompanyID = add.ID,
                BrandName = param.Brand
            };
            dc.Csrd_Brand.Add(brand);
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [JsonType]
        [MustLogin]
        [Description("修改")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Modify([ParamDescription("输入参数")] ModifyData param)
        {
            if (param == null) return Error("对象为空！");
            if (string.IsNullOrWhiteSpace(param.CompanyName)) return Error("公司名称不能为空！");
            if (string.IsNullOrWhiteSpace(param.AccountCode)) return Error("帐号不能为空！");
            if (string.IsNullOrWhiteSpace(param.BankName)) return Error("开户行不能为空！");
            if (string.IsNullOrWhiteSpace(param.CompanyAddress)) return Error("公司地址不能为空！");
            if (string.IsNullOrWhiteSpace(param.TaxNumber)) return Error("税号不能为空！");
            if (string.IsNullOrWhiteSpace(param.Telephone)) return Error("联系电话不能为空！");
            if (string.IsNullOrWhiteSpace(param.Brand)) return Error("品牌不能为空！");
            if (param.CompanyShortName.Length > 100) return Error("【公司简称】长度超出限制");
            if (param.CompanyName.Length > 150) return Error("【公司名称】长度超出限制");
            if (param.AccountCode.Length > 20) return Error("【帐号】长度超出限制");
            if (param.BankName.Length > 50) return Error("【开户行】长度超出限制");
            if (param.CompanyAddress.Length > 200) return Error("【公司地址】长度超出限制");

            var dc = new CsrdEntities();
            if (dc.Csrd_Company.Any(t => t.CompanyName == param.CompanyName && t.ID != param.CompanyID)) return Error("公司名称不能重复！");
            var r = param.Brand.TrimEnd(',').Split(',').ToList();
            var b = dc.Csrd_Brand.Where(t => t.CompanyID != param.CompanyID).Select(t=>t.BrandName).ToList();

            if (r.Any(i => b.Any(j => j.Contains(i))))
            {
                return Error($"品牌{param.Brand}已被使用！");
            }

            var query = dc.Csrd_Company.FirstOrDefault(t => t.ID == param.CompanyID);
            query.CompanyName = param.CompanyName;
            query.CompanyShortName = param.CompanyShortName;
            query.BankName = param.BankName;
            query.AccountCode = param.AccountCode;
            query.CompanyAddress = param.CompanyAddress;
            query.TaxNumber = param.TaxNumber;
            query.Telephone = param.Telephone;
            var brand = dc.Csrd_Brand.FirstOrDefault(t => t.CompanyID == query.ID);
            if (brand != null) brand.BrandName = param.Brand;
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }
        [MustLogin]
        [Description("删除")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Remove([ParamDescription("公司ID")]int CompanyID)
        {
            try
            {
                var dc = new CsrdEntities();
                dc.Csrd_Brand.Where(t => t.CompanyID == CompanyID).Delete();
                dc.Csrd_Company.Where(t => t.ID == CompanyID).Delete();
            }
            catch(Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }


        #region 获取公司资料
        [MustLogin]
        [Description("获取公司资料")]
        [ReturnType(typeof(PaperData<ListData>))]
        public ApiResult GetCompany(string CompanyID)
        {
            var dc = new CsrdEntities();
            var query = (from c in dc.Csrd_Company
                join b in dc.Csrd_Brand on c.ID equals b.CompanyID
                where b.BrandName.Contains(CompanyID)
                select new
                {
                    c.CompanyID,
                    c.CompanyName,
                    c.CompanyAddress,
                    c.AccountCode,
                    c.CompanyShortName,
                    c.TaxNumber,
                    c.BankName,
                    c.ID
                }).FirstOrDefault();
            if(query==null) return  Error("无公司数据");
            var result = new ListData
            {
                CompanyName = query.CompanyName,
                CompanyShortName = query.CompanyShortName,
                TaxNumber = query.TaxNumber,
                AccountCode = query.AccountCode,
                BankName = query.BankName,
                CompanyAddress = query.CompanyAddress
            };
            return Success(result);
        }
        #endregion

    }
}
